<script lang="ts" setup>
import { onMounted, onUnmounted, reactive } from 'vue'
import { dbus } from '@/dbus/dbus.ts'
import { invoke_proxy } from '@/functions/invoke.ts'
import { BackendResponse } from '@/runtime/response.ts'
import { BACKEND_CODE_OK } from '@/runtime/code.ts'
import { copy_to_clipboard } from '@/functions/clipboard.ts'
import { ComponentV2rayInfo } from '@/models/components/v2ray/v2ray_info.ts'
import { ComponentV2rayBasicSetting, new_component_v2ray_basic_setting } from '@/models/components/v2ray/v2ray_basic_setting.ts'

const state = reactive<{ show: boolean; basic_setting: ComponentV2rayBasicSetting; ips: string[] }>({ show: false, basic_setting: new_component_v2ray_basic_setting(), ips: [] })

onMounted(async () => {
    dbus.on('component:v2ray:copy-local-proxy', show)
})

onUnmounted(async () => {
    dbus.off('component:v2ray:copy-local-proxy', show)
})

async function show(): Promise<void> {
    state.show = true

    {
        const response = await invoke_proxy<BackendResponse<ComponentV2rayInfo>>('invoke_component_v2ray_info')
        if (BACKEND_CODE_OK !== response.code) {
            window.Message.error(response.message)

            return
        }

        state.basic_setting = response.data.basic_setting
    }

    {
        const response = await invoke_proxy<BackendResponse<string[]>>('invoke_get_local_ips')
        if (BACKEND_CODE_OK !== response.code) {
            window.Message.error(response.message)

            return
        }

        state.ips = response.data
    }
}

async function copy(ip: string): Promise<void> {
    ip = ip.includes(':') ? `[${ip}]` : ip
    copy_to_clipboard(`export http_proxy="http://${ip}:${state.basic_setting.http_port}"; export https_proxy="http://${ip}:${state.basic_setting.http_port}"; export HTTP_PROXY="http://${ip}:${state.basic_setting.http_port}"; export HTTPS_PROXY="http://${ip}:${state.basic_setting.http_port}"`)
}
</script>

<template>
    <n-modal v-model:show="state.show" class="modal" transform-origin="center">
        <n-card closable @close="state.show = false">
            <n-space :wrap="false" :wrap-item="false" class="ip-list" vertical>
                <template v-for="ip in state.ips" :key="ip">
                    <n-space :wrap="false" :wrap-item="false" align="center">
                        <div class="max-flex-width">{{ ip }}</div>
                        <div>
                            <n-button size="small" type="info" @click="copy(ip)">复制</n-button>
                        </div>
                    </n-space>
                </template>
            </n-space>
        </n-card>
    </n-modal>
</template>

<style lang="scss" scoped>
.modal {
    width: 80vw;
    height: 80vh;
    padding: 15px;
    overflow-y: auto;
}
</style>
